/**
 * Name: Avinash Sridhar	G Number: G00861300
 */
package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;

import udp.Server.PhonebookEntry;

/**
 * @author Avinash
 *
 */
public class ClientRequestHandler extends Thread{

	ArrayList<PhonebookEntry> mPhonebook;
	DatagramSocket mClientSocketPort;
	DatagramSocket mChildrenSocketPort;
	int mParentSocketPort;


	public ClientRequestHandler(ArrayList<PhonebookEntry> phonebook, DatagramSocket clientSocketPort, DatagramSocket childrenSocketPort, int parentSocketPort) {
		mPhonebook = phonebook;
		mClientSocketPort = clientSocketPort;
		mChildrenSocketPort = childrenSocketPort;
		mParentSocketPort = parentSocketPort;

	}

	@Override
	public void run() {
		try{ 
			System.out.println("UDP Server Initialized and Listening for UDP Clients at client port <" + mClientSocketPort.getLocalPort() + ">...");
			while (true) {
				/* Params:
				 * clientSocket - contains Children's current request to the Server
				 * phonebook - contains phonebook of current Server
				 * clientSocketPort - contains the clientSocketPort NUMBER for this Server
				 * childrenSocketPort - contains the childrenSocketPort NUMBER for this Server
				 * parentSocketPort - contains the parentSocketPort NUMBER for this Server
				 */
				int childrenPort;
				if (mChildrenSocketPort == null)
					childrenPort = -1;
				else
					childrenPort = mChildrenSocketPort.getLocalPort();


				byte[] buffer = new byte[4096];
				DatagramPacket clientPacket = new DatagramPacket(buffer, buffer.length);
				mClientSocketPort.receive(clientPacket);	
				new LookupService(clientPacket, mPhonebook, mClientSocketPort.getLocalPort(), childrenPort, mParentSocketPort).start();
			}
		} catch (IOException e) {
			System.out.println("Could not listen on port " + mClientSocketPort.getLocalPort());
			System.exit(0);
		}
	}

}
